import axios from 'axios';
import { message } from 'antd';

const api = import.meta.env.VITE_BASE_URL; //api

//创建一个axios实例
const instance = axios.create({
  baseURL: api, //基础地址
  timeout: 3000, //超时时间
  timeoutErrorMessage: '请求超时,请刷新页面重新尝试', //超时错误信息
  withCredentials: true, //跨域请求时是否需要使用cookie
  headers: {
    'Content-Type': 'application/json', //请求头
    'X-Requested-With': 'XMLHttpRequest', //请求头
    Authorization: 'Bearer' + localStorage.getItem('token'), //请求头
  },
});

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 40001) {
      //跳转到登录页面
      window.location.href = '/login';
    } else if (data.code !== 200) {
      //接口错误
      message.error(data.msg);
    }
    return data.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//导出一个对象，包含get、post、put、delete方法
export default {
  get<T>(url: string, params?: object): Promise<T> {
    return instance.get(url, { params });
  },
  post<T>(url: string, params?: object): Promise<T> {
    return instance.post(url, params);
  },
  put<T>(url: string, params?: object): Promise<T> {
    return instance.put(url, params);
  },
  delete<T>(url: string, params?: object): Promise<T> {
    return instance.delete(url, { params });
  },
};
